{{define "tasks.html"}}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>覆盖率平台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            list-style-type: none;
        }
        header {
            display: flex;
            align-items: center;
            justify-content: space-between; /* 使元素在水平方向两端对齐 */
        } 
        .user-info {
            padding: 15px;
            font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
            font-size: 28px;
            font-weight: bolder;
        }
        ul {
            width: 100%; /* 确保 ul 占满父容器宽度 */
        }
        li {
            width: 100%;
        }
        /* 左侧任务列表样式 */
       .left-section {
            max-width: 500px;
            height: 100vh; /* 设置固定高度，使其成为可滚动窗口 */
            overflow-y: auto; /* 启用垂直滚动 */
            border: 5px solid #ccc;
            padding: 8px;
            width: 30%; /* 让任务列表占浏览器横向30%的空间 */
            box-sizing: border-box; /* 确保边框和内边距包含在宽度内 */
        }
        h2 {
            text-align: center;
            margin-bottom: 10px;
        }
        /* 右侧空白部分样式 */
       .right-section {
            width: 70%; /* 右侧部分占70%的宽度 */
            box-sizing: border-box;
            float: right; /* 使右侧部分浮动到右侧 */
            padding: 10px;
        }

        /* 主体内容部分样式 */
        main {
            display: flex; /* 使用flex布局 */
        }

        /* 任务项样式 */
       .task-item {
            width: 100%;
            border: 1px solid #ddd; /* 添加方框 */
            padding: 10px;
            margin-bottom: 10px;
            transition: background-color 0.3s; /* 过渡效果 */
        }

        /* 悬停时高亮 */
       .task-item:hover {
            background-color: #20a2b3;
        }
        button {
            padding: 8px 16px;
            margin: 0 10px;
            cursor: pointer;
        }
        #api-token-display {
            margin-left: 10px;
            font-weight: bold;
        }
        .button-container {
            display: flex;
        }
        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.4);
        }
        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 400px;
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }
        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <!-- 顶部个人信息部分 -->
    <header>
        <div class="user-info">
            用户名: {{ .username }}
        </div>
        <div class="button-container">
            <button id="apply-api-token">申请 API Token</button>
            <button id="logout">退出登录</button>
        </div>
    </header>
    <!-- 筛选条件 -->
    <div>
        <label for="start-date">开始日期:</label>
        <input type="date" id="start-date">
        <label for="end-date">结束日期:</label>
        <input type="date" id="end-date">
        <button id="filter-button">筛选</button>
    </div>
    <!-- 主体内容部分 -->
    <main>
        <!-- 左侧覆盖率任务列表 -->
        <div class="left-section">
            <h2>覆盖率任务列表</h2>
            <ul id="task-list">
            </ul>
        </div>
        <!-- 右侧空白部分 -->
        <div class="right-section"></div>
    </main>
    <!-- 模态框 -->
    <div id="token-modal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <p id="token-text"></p>
        </div>
    </div>
    <script >
        // 获取用户名
        const username = "{{ .username }}";
        console.log(`username=${username}`);

        // 获取任务列表和右侧空白部分
        const taskList = document.getElementById('task-list');
        const rightSection = document.querySelector('.right-section');

        const pageSize = 10;
        let currentPage = 1;
        let isLoading = false;
        let startDate = '';
        let endDate = '';

        async function fetchTasks(page, start, end) {
            if (isLoading) return;
            isLoading = true;
            try {
                const formData = new URLSearchParams();
                formData.append('username', username);
                formData.append('page', page);
                formData.append('pageSize', pageSize);
                if (start) formData.append('startDate', start);
                if (end) formData.append('endDate', end);
                const response = await fetch(`${window.location.pathname}/gettasks`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'    
                    },
                    body: formData
                });
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const tasks = await response.json();
                renderTasks(tasks);
                isLoading = false;
            } catch (error) {
                console.error('请求出错:', error);
                isLoading = false;
            }
        }

        // 渲染任务列表
        function renderTasks(tasks) {
            tasks.forEach(task => {
                const listItem = document.createElement('li');
                const link = document.createElement('a');
                link.href = '#';
                link.dataset.tid = `${task.Tid}`;
                // link.dataset.repoUrl = task.RepoUrl; // 存储 repoUrl

                const taskItem = document.createElement('div');
                taskItem.classList.add('task-item');

                const data = document.createElement('p')
                data.textContent = `Time: ${task.CreatedAt}`
                const repoUrl = document.createElement('p');
                repoUrl.textContent = `RepoUrl: ${task.RepoUrl}`;
                const taskId = document.createElement('p');
                taskId.textContent = `TID: ${task.Tid}`;
                const coverPercent = document.createElement('p');
                coverPercent.textContent = `Percentage: ${task.Percent}%`;

                taskItem.appendChild(data);
                taskItem.appendChild(taskId);
                taskItem.appendChild(repoUrl);
                taskItem.appendChild(coverPercent);
                
                link.appendChild(taskItem);
                listItem.appendChild(link);
                taskList.appendChild(listItem);

                // 为每个列表项添加点击事件监听器
                link.addEventListener('click', async (event) => {
                    event.preventDefault();

                    const tid = link.dataset.tid;

                    window.open(`/tasks/task/${tid}`)
                });
            });
        };

        // 监听滚动事件
        document.querySelector('.left-section').addEventListener('scroll', function() {
            if (this.scrollTop + this.clientHeight >= this.scrollHeight - 100 && !isLoading) {
                currentPage++;
                fetchTasks(currentPage, startDate, endDate);
            }
        });

        // 筛选按钮点击事件
        const filterButton = document.getElementById('filter-button');
        filterButton.addEventListener('click', () => {
            startDate = document.getElementById('start-date').value;
            endDate = document.getElementById('end-date').value;
            if (startDate && endDate && new Date(startDate) > new Date(endDate)) {
                console.log('开始日期不能晚于结束日期，不发送请求');
                return;
            }
            currentPage = 1;
            taskList.innerHTML = '';
            fetchTasks(currentPage, startDate, endDate);
        });

        // 页面加载时获取第一页任务数据
        window.addEventListener('load', () => {
            fetchTasks(currentPage, startDate, endDate);
        });

        // 申请 API Token 按钮点击事件
        const applyApiTokenButton = document.getElementById('apply-api-token');
        const tokenModal = document.getElementById('token-modal');
        const tokenText = document.getElementById('token-text');
        const copyTokenButton = document.getElementById('copy-token');
        const closeModal = document.querySelector('.close');

        applyApiTokenButton.addEventListener('click', async () => {
            try {
                const formData = new FormData();
                formData.append('username', username);
                const response = await fetch('/apply-api-token', {
                    method: 'POST',
                    body: formData
                });
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const data = await response.json();

                // 显示模态框
                tokenText.textContent = `API Token: ${data.token}`;
                tokenModal.style.display = "block";
            } catch (error) {
                console.error('申请 API Token 出错:', error);
            }
        });

        // 关闭模态框
        closeModal.addEventListener('click', () => {
            tokenModal.style.display = "none";
        });

        // 点击模态框外部关闭模态框
        window.addEventListener('click', (event) => {
            if (event.target == tokenModal) {
                tokenModal.style.display = "none";
            }
        });

        // 退出登录按钮点击事件
        const logoutButton = document.getElementById('logout');
        logoutButton.addEventListener('click', async () => {
            try {
                const formData = new FormData();
                formData.append('username', username);
                const response = await fetch('/logout', {
                    method: 'POST',
                    body: formData
                });
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                window.location.href = '/index';
            } catch (error) {
                console.error('退出登录出错:', error);
            }
        });
    </script>
</body>

</html>
{{end}}    